package com.opennews.openplatform.util;

import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.apache.flink.shaded.jackson2.org.yaml.snakeyaml.Yaml;

import java.util.Map;

public class NacosConfigLoader {
    public static Map<String, Object> loadNacosConfig(String dataId, String groupId) throws NacosException {
        Map<String, Object> localConfig = YamlConfigLoader.loadYamlConfig();
        Map<String, Object> springConfig = (Map<String, Object>) localConfig.get("spring");
        Map<String, Object> cloudConfig = (Map<String, Object>) springConfig.get("cloud");
        Map<String, Object> nacosConfig = (Map<String, Object>) cloudConfig.get("nacos");
        String serverAddr = (String) nacosConfig.get("server-addr");

        // Creates Nacos ConfigService instance
        ConfigService configService = ConfigFactory.createConfigService(serverAddr);

        // Fetches configuration from Nacos
        String content = configService.getConfig(dataId, groupId, 5000);
        Yaml yaml = new Yaml();
        Map<String, Object> config = yaml.load(content);

        return config;
    }

    public static Map<String, Object> loadNacosConfig(String dataId) throws NacosException {
        return loadNacosConfig(dataId, "DEFAULT_GROUP");
    }

    public static Map<String, Object> loadKafkaConfig() throws NacosException {
        Map<String, Object> config = loadNacosConfig("kafka.yml");
        Map<String, Object> springConfig = (Map<String, Object>) config.get("spring");
        Map<String, Object> kafkaConfig = (Map<String, Object>) springConfig.get("kafka");

        return kafkaConfig;
    }
}
